package com.shiro.demo.common;

import com.shiro.demo.db.entity.Logininfor;
import com.shiro.demo.db.service.ILogininforService;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;

@Slf4j
public class LoginLogUtils {
    /**
     * 记录格式 [ip][用户名][操作][错误消息]
     * <p/>
     * 注意操作如下： loginError 登录失败 loginSuccess 登录成功 passwordError 密码错误 changePassword 修改密码 changeStatus 修改状态
     *
     *
     */
    public static void log(String username, String status, String msg, Object... args)
    {
        String host = ShiroUtils.getHost();
        String loginLocation = AddressUtils.getRealAddressByIP(ShiroUtils.getHost());

        StringBuilder s = new StringBuilder();
        s.append(getBlock(host));
        s.append(getBlock(loginLocation));
        s.append(getBlock(username));
        s.append(getBlock(status));
        s.append(getBlock(msg));

        log.info(s.toString(), args);

        if (LoginConstants.LOGIN_SUCCESS.equals(status) || LoginConstants.LOGOUT.equals(status))
        {
            saveLogininfor(username,host, loginLocation, msg, LoginConstants.LOGIN_SUCCESS);
        }
        else if (LoginConstants.LOGIN_FAIL.equals(status))
        {
            saveLogininfor(username, host, loginLocation, msg, LoginConstants.LOGIN_FAIL);
        }
    }

    /**
     * 持久化登录日志
     * @param username
     * @param msg
     * @param status
     */
    protected static void saveLogininfor(String username, String host, String loginLocation, String msg, String status){
        Logininfor logininfor = new Logininfor();
        logininfor.setLoginName(username);
        logininfor.setIpaddr(host);

        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequestHeader("User-Agent"));
        logininfor.setBrowser(userAgent.getBrowser().getName());
        logininfor.setOs(userAgent.getOperatingSystem().getName());

        logininfor.setStatus(status);
        logininfor.setMsg(msg);
        logininfor.setLoginTime(LocalDateTime.now());

        ILogininforService logininforService = SpringUtils.getBean(ILogininforService.class);
        logininforService.save(logininfor);
    }

    public static String getBlock(String msg){
        return "[" + msg +  "]";
    }
}
